var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var debug = require('debug')('shoppingoverseas:server');
var session = require('express-session');
var SessionStore = require("connect-mongo")(session);
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var http = require('http');
var fs = require('fs');
var routes = require('./routes');
var app = express();
//视图模板
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.set('trust proxy', 1);
app.use(session({
    resave:false,//添加这行
    saveUninitialized: true,//添加这行
    secret:"hmlovepinyao",
    rolling:true,
    store:new SessionStore({
        url:"mongodb://120.55.114.198:4000/session",
        interval:60*60*24*30
    }),
    cookie: { path: '/', httpOnly: true, secure: false, maxAge: 60*60*24*30,expires:new Date().getTime()+1000*60*60*24*30 }
}));

routes(app);
//静态文件加载
app.use(express.static(path.join(__dirname, '/')));

//app.use(function(req, res, next) {
//    var err = new Error('Not Found');
//    err.status = 404;
//    next(err);
//});

if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        console.log(err);
        res.status(err.status || 500);
        console.log(err);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

var port = normalizePort(process.env.PORT || '5001');
app.set('port', port);

//创建https服务器
//var options = {
//    pfx:fs.readFileSync('./keys/server.pfx'),
//    passphrase:'123123'
//};
var server = http.createServer(app);
server.listen(port);
console.log("server is running on port "+ port );

server.on('error', onError);
server.on('listening', onListening);

function normalizePort(val) {
    var port = parseInt(val, 10);
    if (isNaN(port)) {
        return val;
    }
    if (port >= 0) {
        return port;
    }
    return false;
}
function onError(error) {
    if (error.syscall !== 'listen') {
        throw error;
    }
    var bind = typeof port === 'string'
        ? 'Pipe ' + port
        : 'Port ' + port;
    switch (error.code) {
        case 'EACCES':
            console.error(bind + ' requires elevated privileges');
            process.exit(1);
            break;
        case 'EADDRINUSE':
            console.error(bind + ' is already in use');
            process.exit(1);
            break;
        default:
            throw error;
    }
}
function onListening() {
    var addr = server.address();
    var bind = typeof addr === 'string'
        ? 'pipe ' + addr
        : 'port ' + addr.port;
    debug('Listening on ' + bind);
}
module.exports = app;
